<template>
  <div class="questionnaire-detail" v-loading="loading">
    <ElBacktop :right="100" :bottom="100" target=".questionnaire-detail" />
    <div
      class="sticky h-50px top-0 left-0 z-10 flex items-center justify-center bg-[var(--top-header-bg-color)] layout-border__bottom"
    >
      <Logo class="custom-hover !pr-15px absolute top-0 left-0" />
      <div class="font-700 text-18px text-[var(--top-header-text-color)]">问卷调查</div>
    </div>

    <div v-if="baseData?.id" class="questionnaire-detail-container">
      <div class="detail-section">
        <div class="section-label">{{ baseData.title }}</div>
        <div v-if="baseData.remark" class="content-container">
          <div class="content-text">{{ baseData.remark }}</div>
        </div>
      </div>
      <form-create
        v-model="detailData.value"
        v-model:api="fApi"
        :rule="detailData.rule"
        :option="detailData.option"
        @submit="onSubmit"
      />
    </div>
    <div v-else class="questionnaire-detail-container">
      <el-empty v-if="!loading" description="无问卷调查内容，请先检查问卷地址或创建问卷">
        <el-button type="primary" @click="handleClose">关闭</el-button>
      </el-empty>
    </div>

    <Footer />
    <el-dialog v-model="dialogVisible" fullscreen :show-close="false" :close-on-click-modal="false">
      <div class="text-center text-22px flex flex-col items-center w-full justify-center m-t-15vh">
        <div
          ><el-icon><Document /></el-icon> 问卷到此结束，感谢您的参与</div
        >
        <el-button type="primary" class="m-t-20px" @click="handleClose">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { Document } from '@element-plus/icons-vue'
import formCreate from '@form-create/element-ui'
import { setConfAndFields2 } from '@/utils/formCreate'
import { QuestionnaireApi, QuestionnaireVO } from '@/api/school/questionnaire'
import { QuestionnaireRecordApi, QuestionnaireRecordVO } from '@/api/school/questionnaire/record'
import { useRoute } from 'vue-router'
import { Logo } from '@/layout/components/Logo'
import { ElBacktop } from 'element-plus'
import { Footer } from '@/layout/components/Footer'
const { params } = useRoute() // 路由信息
const message = useMessage() // 消息
const loading = ref(true)
const fApi: any = ref(null)
const detailData = ref({
  value: {},
  rule: [],
  option: {}
})
const baseData = ref<QuestionnaireVO>({} as QuestionnaireVO)
const dialogVisible = ref(false)
const formatRule = (rule: any[]) => {
  rule.forEach((item: any) => {
    item.field = item.field + '|' + item.title
  })
}
const getDetail = async (url) => {
  try {
    loading.value = true
    const data = await QuestionnaireApi.getQuestionnaireByUrl({
      formUrl: url
    })
    baseData.value = data
    const formJson = JSON.parse(data.formJson || '{}')
    setConfAndFields2(detailData, formJson.conf, formJson.fields, formJson.value)
    formatRule(detailData.value.rule)
  } catch (e) {
    console.log(e, '--error')
  } finally {
    await nextTick()
    loading.value = false
  }
}
const onSubmit = async (formData) => {
  let sendContent: any = {
    data: {
      createdTime: new Date().getTime()
    },
    labelList: [
      {
        label: '填报时间',
        key: 'createdTime'
      }
    ]
  }
  for (const key in formData) {
    const newKey = key.split('|')[0]
    const label = key.split('|')[1]
    sendContent.data[newKey] = formData[key] || '--'
    if (label) {
      sendContent.labelList.push({
        label: label,
        key: newKey
      })
    }
  }
  // const formJson = JSON.parse(baseData.value.formJson || '{}')
  // formJson.value = formData
  // baseData.value.formJson = JSON.stringify(formJson)
  try {
    // await QuestionnaireApi.updateQuestionnaire(baseData.value)
    await QuestionnaireRecordApi.createQuestionnaireRecord({
      qsId: baseData.value.id,
      dataJson: JSON.stringify(sendContent)
    })
    message.success('问卷填写完成')
    dialogVisible.value = true
  } catch (error) {
    console.error('提交问卷失败:', error)
    return
  }
}
const handleClose = () => {
  window.location.replace('about:blank')
  window.close()
}
onMounted(() => {
  if (params.shortCode) getDetail(params.shortCode)
})
</script>
<style lang="scss" scoped>
.questionnaire-detail {
  position: relative;
  height: 100%;
  overflow: auto;
}

.questionnaire-detail-container {
  max-width: 900px;
  min-height: calc(100vh - var(--app-footer-height) - 50px - 40px);
  padding: 25px;
  margin: 20px auto;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}

.detail-section {
  margin-bottom: 25px;

  &:last-child {
    margin-bottom: 0;
  }
}

.section-label {
  position: relative;
  padding-left: 12px;
  margin-bottom: 12px;
  font-size: 16px;
  font-weight: 600;
  color: #606266;
}

.section-label::before {
  position: absolute;
  top: 5px;
  bottom: 5px;
  left: 0;
  width: 4px;
  background-color: var(--el-color-primary);
  border-radius: 2px;
  content: '';
}

.content-text {
  color: var(--el-text-color-secondary);
}
</style>
